<?php
class Image extends AppModel {
    var $name = 'Image';
    var $useTable     = 'images';
    var $displayField = 'filename';
    var $belongsTo    = array(
        'Album' => array(
            'className'    => 'Album',
            'foreignKey'   => 'album_id',
            'counterCache' => true
        )
    );

    public function deleteImage ($id) {
        $sql  = 'SELECT `id` FROM `albums` AS a WHERE `image_id`='.$id;
        $data = $this->query($sql);

        $aid = (count($data) > 0) ? $data[0]['a']['id'] : false;

        if ($this->delete($id)) {
            if (!$aid) { // check if delete image is album's cover image, replace another image if yes..
                return true;
            }

            $data = $this->find('first', array(
                'conditions' => array('Image.album_id' => $aid),
                'recursive'  => -1,
                'fields'     => array('Image.id'),
                'order'      => array('Image.id')
            ));

            $iid = (!$data) ? 0 : $data['Image']['id'];
            $sql = 'UPDATE `albums` SET `image_id`='.$iid.' WHERE `id`='.$aid;
            $this->query($sql);

            return true;
        }

        return false;
    } // deleteImage
} // Image
?>